﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;
using Yule8xCommon.Typelib;
using Yule8xModel;
using Yule8xModel.PageModels;

namespace Yule8xWechat.XAgent
{
    public partial class Kaidanshenqi : System.Web.UI.Page
    {
        protected XPageData pageData;
        protected WxUserInfoResult wxUser;
        protected int user_id;
        protected IList<Agent1Record> agent1List;
        protected IList<Agent2Record> agent2List;
        protected IList<IncomeRecord> incomeList;
        protected void Page_Load(object sender, EventArgs e)
        {
            // 接收表单参数
            int agent1_count = RequestUtil.GetInteger("agent1_count");
            int agent2_count = RequestUtil.GetInteger("agent2_count");
            int base_income = RequestUtil.GetInteger("base_income");
            int base_agent1_count = RequestUtil.GetInteger("base_agent1_count");
            int base_agent2_count = RequestUtil.GetInteger("base_agent2_count");
            int diamond = RequestUtil.GetInteger("diamond");
            user_id = RequestUtil.GetInteger("user_id");
            if (user_id < 1)
            {
                Response.Write("user_id无效!");
                Response.End();
            }
            wxUser = UserModels.GetWxUserInfo(user_id);
            if (null == wxUser)
            {
                Response.Write("用户不存在!");
                Response.End();
            }

            IList<string> nicknamesList = new List<string>();
            string sqlstmt;
            int istart, iend, agent_all_count = agent1_count + agent2_count;
            Random rnd = new Random();
            // 随机从数据库或文本文件读取随机名字
            string nickname_filepath = RuntimeDataUtil.filePathes.nicknames_file;
            if (System.IO.File.Exists(nickname_filepath) && (rnd.Next(10) % 2 < 1))
            {
                string nicknamecontent = System.IO.File.ReadAllText(nickname_filepath);
                if (nicknamecontent.Length > 1)
                {
                    nicknamesList = nicknamecontent.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    ArrayUtil.RandomArray<string>(ref nicknamesList);
                }
            }
            if (nicknamesList.Count < 1)
            {
                sqlstmt = string.Format("select top {0} nickname from t_user WHERE nickname <> '' order by NEWID()", agent_all_count);
                DataTable dtnames = DbFactory.Init(AppInfo.conn_yule8x_agent).ExecuteDataTable(sqlstmt);
                foreach (DataRow r in dtnames.Rows)
                {
                    nicknamesList.Add(r["nickname"].ToString());
                }
            }

            // ===========================1级代理===========================
            agent1List = new List<Agent1Record>();
            istart = 0;
            iend = agent1_count;
            for (int i = istart; i < iend; i++)
            {
                agent1List.Add(new Agent1Record() { nickname = nicknamesList[i], rebate_amount_today = 75, rebate_amount_total = 75, agent_count = 0 });
            }
            // ===========================2级代理===========================
            agent2List = new List<Agent2Record>();
            istart = agent1_count;
            iend = agent_all_count;
            for (int i = istart; i < iend; i++)
            {
                agent2List.Add(new Agent2Record() { nickname = nicknamesList[i], rebate_amount_today = 45, rebate_amount_total = 45 });
            }
            // 随机给1级代理补全数据
            int n = rnd.Next(agent2_count); // 2级对应的1级的数量
            int agentcount, agent2_rnd, agent2_remain = agent2_count;
            for (int i = 0; i < agent2_count; i++)
            {
                if (agent2_remain < 1)
                {
                    break;
                }
                agent2_rnd = rnd.Next(agent2_count);
                if (agent2_rnd > agent2_remain)
                {
                    agent2_rnd = agent2_remain;
                }
                agent2_remain -= agent2_rnd;
                agentcount = agent2_rnd;
                agent1List[i].agent_count = agentcount;
                agent1List[i].rebate_amount_today += agentcount * 45;
                agent1List[i].rebate_amount_total += agent1List[i].rebate_amount_today;
            }
            // ===========================今日收入===========================
            incomeList = new List<IncomeRecord>();
            foreach (Agent1Record a in agent1List)
            {
                incomeList.Add(new IncomeRecord() { amount = 75, remark = string.Format("[{0}]1级注册返佣", a.nickname) });
            }
            foreach (Agent2Record a in agent2List)
            {
                incomeList.Add(new IncomeRecord() { amount = 45, remark = string.Format("[{0}]2级注册返佣", a.nickname) });
            }
            if (incomeList.Count > 1)
            {
                ArrayUtil.RandomArray<IncomeRecord>(ref incomeList); // 打乱顺序

                int seconds = (int)(DateTime.Now - DateTime.Parse("9:00:00")).TotalSeconds;
                int seconds_temp = 0;
                int seconds_rnd = seconds / incomeList.Count;
                for (int i = 0; i < incomeList.Count; i++)
                {
                    seconds_temp += rnd.Next(seconds_rnd);
                    if (seconds_temp > seconds)
                    {
                        seconds_temp = seconds;
                    }
                    incomeList[i].datetime = DateTime.Now.AddSeconds(-seconds_temp).ToString("MM-dd HH:mm");
                }
            }
            // ===========================计算页面统计===========================
            pageData = new XPageData()
            {
                diamond = diamond,
                agent1_commission_today = agent1_count * 75,
                agent1_count_today = agent1_count,
                agent1_count_total = agent1_count + base_agent1_count,
                agent2_commission_today = agent2_count * 45,
                agent2_count_today = agent2_count,
                agent2_count_total = agent2_count + base_agent2_count,
            };
            pageData.agent1_commission_total = pageData.agent1_commission_today + base_agent1_count * 75;
            pageData.agent2_commission_total = pageData.agent2_commission_today + base_agent2_count * 45;
            pageData.income_today = pageData.agent1_commission_today + pageData.agent2_commission_today;
            pageData.income_total = pageData.agent1_commission_total + pageData.agent2_commission_total;
            pageData.blance = base_income + pageData.income_today;
        }

        protected string ShortText(object value, int length, string defv = "-")
        {
            return StringUtil.Substring(value, length, defv);
        }
        /// <summary>
        /// 今日收入记录
        /// </summary>
        public class IncomeRecord
        {
            /// <summary>
            /// 时间
            /// </summary>
            public string datetime { get; set; }
            /// <summary>
            /// 收入金额
            /// </summary>
            public decimal amount { get; set; }
            /// <summary>
            /// 收入来源
            /// </summary>
            public string remark { get; set; }
        }
        /// <summary>
        /// 1级代理数据
        /// </summary>
        public class Agent1Record
        {
            /// <summary>
            /// 昵称
            /// </summary>
            public string nickname { get; set; }
            /// <summary>
            /// 当日收入
            /// </summary>
            public decimal rebate_amount_today { get; set; }
            /// <summary>
            /// 累计收入
            /// </summary>
            public decimal rebate_amount_total { get; set; }
            /// <summary>
            /// 下线数量
            /// </summary>
            public int agent_count { get; set; }
        }
        /// <summary>
        /// 2级代理数据
        /// </summary>
        public class Agent2Record
        {
            /// <summary>
            /// 昵称
            /// </summary>
            public string nickname { get; set; }
            /// <summary>
            /// 当日收入
            /// </summary>
            public decimal rebate_amount_today { get; set; }
            /// <summary>
            /// 累计收入
            /// </summary>
            public decimal rebate_amount_total { get; set; }
        }
        /// <summary>
        /// 页面统计数据
        /// </summary>
        public class XPageData
        {
            /// <summary>
            /// 账户余额
            /// </summary>
            public decimal blance { get; set; }
            /// <summary>
            /// 钻石数量
            /// </summary>
            public int diamond { get; set; }

            /// <summary>
            /// 1级代理今日新增数量
            /// </summary>
            public int agent1_count_total { get; set; }
            /// <summary>
            /// 1级代理总数量
            /// </summary>
            public int agent1_count_today;
            /// <summary>
            /// 1级代理今日收入
            /// </summary>
            public decimal agent1_commission_today { get; set; }
            /// <summary>
            /// 1级代理总收入
            /// </summary>
            public decimal agent1_commission_total { get; set; }

            /// <summary>
            /// 2级代理今日新增数量
            /// </summary>
            public int agent2_count_total;
            /// <summary>
            /// 2级代理总数量
            /// </summary>
            public int agent2_count_today;
            /// <summary>
            /// 2级代理今日收入
            /// </summary>
            public decimal agent2_commission_today { get; set; }
            /// <summary>
            /// 2级代理总收入
            /// </summary>
            public decimal agent2_commission_total { get; set; }

            /// <summary>
            /// 累计收入
            /// </summary>
            public decimal income_total { get; set; }
            /// <summary>
            /// 今日收入
            /// </summary>
            public decimal income_today { get; set; }
        }
    }
}